package com.tool.shiro.dao.impl;

import com.tool.shiro.dao.ShiroResourceDao;
import com.tool.shiro.pojo.Pack.MyRowMapperForResource;
import com.tool.shiro.pojo.ShiroResource;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * 数据库操作具体实现类
 * SQLTemplate: SQL语句模板
 * SQL: 真正执行的SQL语句
 * 注: SQL注入等问题待调试和解决
 */
@Repository
public class ShiroResourceDaoImpl implements ShiroResourceDao {

    @Resource
    JdbcTemplate jdbcTemplate;

    @Override
    public List<ShiroResource> getAllShiroResourceInfo() {
        String SQL = "SELECT id, type, `value`, method, description, control FROM shiro_resource;";
        try {
            return jdbcTemplate.query(SQL, new MyRowMapperForResource());
        } catch (Exception e) {
            System.out.println("错误");
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<ShiroResource> getShiroResourceInfoByType(String type) {
        String SQL = "SELECT * FROM shiro_resource WHERE type = ?;";
        try {
            return jdbcTemplate.query(SQL, new MyRowMapperForResource(), type);
        } catch (Exception e) {
            System.out.println("错误");
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int InitializationShiroResource(List<ShiroResource> shiroResources) {
        String SQL = "INSERT INTO shiro_resource (type, `value`, method, description, control) VALUES (?, ?, ?, ?, ?);";
        try {
            jdbcTemplate.batchUpdate(SQL, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int i) throws SQLException {
                    ps.setString(1, shiroResources.get(i).getType());
                    ps.setString(2, shiroResources.get(i).getValue());
                    ps.setString(3, shiroResources.get(i).getMethod());
                    ps.setString(4, shiroResources.get(i).getDescription());
                    ps.setString(5, shiroResources.get(i).getControl());
                }

                @Override
                public int getBatchSize() {
                    return shiroResources.size();
                }
            });
        }catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int deleteShiroResourcesByType(String type) {
        String SQL = "DELETE FROM shiro_resource WHERE type = ?;";
        try {
            jdbcTemplate.update(SQL, type);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

}
